package com.force.abril.api.maintanence.client;

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.springframework.oxm.Marshaller;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.client.core.WebServiceMessageCallback;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.xml.transform.StringSource;

import com.force.abril.api.maintanence.client.request.SessionHeader;
import com.force.provider.SalesForceConnectionProvider;
import com.topi.integration.transformer.helper.MessageSourceConverterHelper;

public class SalesForceSessionHeaderCallback implements
		WebServiceMessageCallback {

	private static final Logger logger = Logger.getLogger(SalesForceSessionHeaderCallback.class);
	
	private WebServiceTemplate wsTemplate;

	private SalesForceConnectionProvider connectionProvider;
	
	public SalesForceSessionHeaderCallback() {
	}

	public SalesForceSessionHeaderCallback(WebServiceTemplate wsTemplate,
			SalesForceConnectionProvider connectionProvider) {
		this.wsTemplate = wsTemplate;
		this.connectionProvider = connectionProvider;
	}

	public SessionHeader buildSessionHeader() {
		SessionHeader session = new SessionHeader();
		session.setSessionId(connectionProvider.getSessionId());
		return session;
	}

	@Override
	public void doWithMessage(WebServiceMessage message) throws IOException,
			TransformerException {

		Source source = message.getPayloadSource();

		StringWriter writer = new StringWriter();

		Marshaller marchaller = wsTemplate.getMarshaller();

		marchaller.marshal(buildSessionHeader(), new StreamResult(writer));

		SoapHeader soapHeader = ((SoapMessage) message).getSoapHeader();

		Transformer transformer = TransformerFactory.newInstance().newTransformer();

		transformer.transform(new StringSource(writer.toString()),
				soapHeader.getResult());
		
		MessageSourceConverterHelper converter = new MessageSourceConverterHelper();
		
		logger.info(converter.convertToString(soapHeader.getSource()));
		

	}

	public WebServiceTemplate getWsTemplate() {
		return wsTemplate;
	}

	public void setWsTemplate(WebServiceTemplate wsTemplate) {
		this.wsTemplate = wsTemplate;
	}

	public SalesForceConnectionProvider getConnectionProvider() {
		return connectionProvider;
	}

	public void setConnectionProvider(
			SalesForceConnectionProvider connectionProvider) {
		this.connectionProvider = connectionProvider;
	}

}
